package lockAndCondition;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo {

	Map<String, Object> cacheMap=new HashMap<String, Object>();
	
	ReadWriteLock lock=new ReentrantReadWriteLock();
	
	public Object getData(String key){
		lock.readLock().lock();
		Object object=cacheMap.get(key);
		if(object==null){
			lock.readLock().unlock();
			lock.writeLock().lock();
			if(object==null){//多判断一次，预防多个写线程都去数据库取数据，填入缓存
				object="data from database";
				cacheMap.put(key, object);
			}
			lock.writeLock().unlock();
			lock.readLock().lock();
		}
		lock.readLock().unlock();
		return object;
	}
}
